package com.gxd.es.service;

import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.frameworkset.elasticsearch.ElasticSearchException;
import org.frameworkset.elasticsearch.ElasticSearchHelper;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.frameworkset.elasticsearch.entity.ESDatas;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

@Component
public class AddressNavByEs {


    public HashSet<String>  search(String key,String cityCode) {

        ElasticTransportClient ElasticTransportClient = new ElasticTransportClient();
        long startime = System.currentTimeMillis();
        MultiSearchResponse SearchResponse = ElasticTransportClient.search(key,cityCode);

        Map tmpMap = new HashMap<>();
        HashSet<String> idSet = new HashSet<String>();
        HashSet<String> resultSet = new HashSet();

        String addressId = null,street = null,fullName = null ,addressName = null;
        for (MultiSearchResponse.Item item : SearchResponse.getResponses()) {
            org.elasticsearch.action.search.SearchResponse response = item.getResponse();

            for (SearchHit hit : response.getHits().getHits()) {
                Map<String, Object> indexMap = new HashMap();
                indexMap = hit.getSourceAsMap();
                addressId = indexMap.get("ADDRESS_ID") == null ? "" : indexMap.get("ADDRESS_ID").toString();
                if (hit.getIndex().equals("address")) {
                    fullName = indexMap.get("FULL_NAME") == null ? "" : indexMap.get("FULL_NAME").toString();
                    resultSet.add("{ADDRESS_ID:" + addressId + ",FULL_NAME:" + fullName + "}");
                } else if (hit.getIndex().equals("street")) {
                    street = indexMap.get("STREET") == null ? "" : indexMap.get("STREET").toString();
                    tmpMap.put(addressId, street);
                    idSet.add(addressId);
                } else {
                    addressName = indexMap.get("ADDRESS_NAME") == null ? "" : indexMap.get("ADDRESS_NAME").toString();
                    tmpMap.put(addressId, addressName);
                    idSet.add(addressId);
                }

            }
        }

        SearchResponse responseById = ElasticTransportClient.termsSearch(idSet);

        for (SearchHit hit : responseById.getHits().getHits()) {
            Map<String, Object> map = hit.getSourceAsMap();
            addressId = map.get("ADDRESS_ID") == null ? "" : map.get("ADDRESS_ID").toString();
            fullName = map.get("FULL_NAME") == null ? "" : map.get("FULL_NAME").toString();
            resultSet.add("{ADDRESS_ID:" + addressId+ ",FULL_NAME:" + fullName + "_" + tmpMap.get(map.get("ADDRESS_ID")) + "}");
        }

        System.out.println(resultSet);
        System.out.println("查询共消耗时间：" + (System.currentTimeMillis() - startime) + "ms");
        return  resultSet;
    }

    /**
     * 检索文档
     * @throws ParseException
     */
    public HashSet testSearchAddress(String keyword, String cityCode) throws ParseException {
        HashSet<String> resultSet = null;
        try {
            //创建加载配置文件的客户端工具，用来检索文档，单实例多线程安全
            ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/demo.xml");
            //设定查询条件,通过map传递变量参数值,key对于dsl中的变量名称
            Map<String,Object> params = new HashMap<String,Object>();
            //设置applicationName1和applicationName2两个变量的值
            params.put("keyword",keyword);
            params.put("cityCode",cityCode);
            params.put("size",5);

            long st = System.currentTimeMillis();
            //执行查询，address为索引表，_search为检索操作action
            ESDatas<Map> addressesDatas =  //ESDatas包含当前检索的记录集合，最多1000条记录，由dsl中的size属性指定
                    clientUtil.searchList("address/_search",//demo为索引表，_search为检索操作action
                            "searchAddress",//esmapper/demo.xml中定义的dsl语句
                            params,//变量参数
                            Map.class);//返回的文档封装对象类型

            // 累计耗时计算
            long dis = System.currentTimeMillis() - st;
            System.out.println("耗时00：" + dis + " ms");

            //执行查询，addressalias为索引表，_search为检索操作action
            ESDatas<Map> addressAliasDatas =  //ESDatas包含当前检索的记录集合，最多1000条记录，由dsl中的size属性指定
                    clientUtil.searchList("addressalias/_search",//addressalias为索引表，_search为检索操作action
                            "searchAddressAlias",//esmapper/demo.xml中定义的dsl语句
                            params,//变量参数
                            Map.class);//返回的文档封装对象类型

            //执行查询，street，_search为检索操作action
            ESDatas<Map> streetDatas =  //ESDatas包含当前检索的记录集合，最多1000条记录，由dsl中的size属性指定
                    clientUtil.searchList("street/_search",//addressalias为索引表，_search为检索操作action
                            "searchStreet",//esmapper/demo.xml中定义的dsl语句
                            params,//变量参数
                            Map.class);//返回的文档封装对象类型

            //获取结果对象列表，最多返回5条记录
            List<Map> addresses = addressesDatas.getDatas();
            List<Map> aliases = addressAliasDatas.getDatas();
            List<Map> streets = streetDatas.getDatas();

            // 构建返回值
            Map tmpMap = new HashMap();
            resultSet = new HashSet();
            HashSet<String> idSet = new HashSet<String>();

            // addresss
            for (Map addr : addresses) {
                resultSet.add("{ADDRESS_ID:" + addr.get("ADDRESS_ID") + ",FULL_NAME:" + addr.get("FULL_NAME") + "}");
            }
            // aliases
            for (Map alias : aliases) {
                idSet.add(alias.get("ADDRESS_ID").toString());
                tmpMap.put(alias.get("ADDRESS_ID"), alias.get("ADDRESS_NAME"));
            }
            // streets
            for (Map street : streets) {
                idSet.add(street.get("ADDRESS_ID").toString());
                tmpMap.put(street.get("ADDRESS_ID"), street.get("STREET"));
            }

            // 累计耗时计算
            dis = System.currentTimeMillis() - st;
            System.out.println("耗时0：" + dis + " ms");

            params.put("addrids", idSet);
            //执行查询，address，_search为检索操作action
            addressesDatas =  //ESDatas包含当前检索的记录集合，最多1000条记录，由dsl中的size属性指定
                    clientUtil.searchList("address/_search",//address为索引表，_search为检索操作action
                            "searchByAddressId",//esmapper/demo.xml中定义的dsl语句
                            params,//变量参数
                            Map.class);//返回的文档封装对象类型

            // 累计耗时计算
            dis = System.currentTimeMillis() - st;
            System.out.println("耗时1：" + dis + " ms");

            // addresss
            addresses = addressesDatas.getDatas();
            for (Map addr : addresses) {
                resultSet.add("{ADDRESS_ID:" + addr.get("ADDRESS_ID") + ",FULL_NAME:" + addr.get("FULL_NAME") + "_" + tmpMap.get(addr.get("ADDRESS_ID")) + "}");
            }

            // 累计耗时计算
            dis = System.currentTimeMillis() - st;
            System.out.println("耗时2：" + dis + " ms");
        } catch (ElasticSearchException e) {
            e.printStackTrace();
        }

        return resultSet;
    }
}
